package com.UnionPayCenter.interceptor;

import com.UnionPayCenter.constant.ConstantInterface;
import com.UnionPayCenter.entity.ResponseWrapper;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.jwt.CurrentManager;
import com.UnionPayCenter.jwt.CurrentShop;
import com.UnionPayCenter.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @program: UnionPayCenter
 * @description:
 * @author: bite
 * @create: 2019-03-11 17:43
 **/
@Slf4j
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        CurrentManager currentManager = handlerMethod.getMethodAnnotation(CurrentManager.class);
        if (currentManager == null) {
            currentManager = handlerMethod.getBeanType().getAnnotation(CurrentManager.class);
        }
        //方法注解判断是否需要token值
        if (currentManager != null && currentManager.value()) {
            JSONObject json = getRequestJsonObject(request);
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                token = request.getHeader("token");
            }

            if (StringUtils.isBlank(token)) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(ResponseWrapper.failed(ErrorCodeEnum.TK1009)));
                return false;
            }

        }
        //方法注解判断是否需要shopId值
        CurrentShop currentShop = handlerMethod.getMethodAnnotation(CurrentShop.class);
        if (currentShop == null) {
            currentShop = handlerMethod.getBeanType().getAnnotation(CurrentShop.class);
        }
        if (currentShop != null) {
            JSONObject json = getRequestJsonObject(request);

            if (!json.containsKey("shopId") || json.get("shopId") == null) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(ResponseWrapper.failed(ErrorCodeEnum.TK1010)));
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }


    public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
        try {
            BufferedReader br = request.getReader();
            String str = null, retStr = "";
            while ((str = br.readLine()) != null) {
                retStr += str;
            }
            if (StringUtils.isNotBlank(retStr)) {
                JSONObject jsonObject = JSONObject.parseObject(retStr);
                return jsonObject;
            }
        } catch (Exception e) {
        }
        return null;
    }

    /***
     * 获取 request 中 json 字符串的内容
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8).replaceAll("%22",
                    "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**
     * 描述:获取 post 请求内容
     */
    public static String getRequestPostStr(HttpServletRequest request) throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = ConstantInterface.ENCODING_FORMAT_UTF8;
        }
        return new String(buffer, charEncoding);
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {
            int readlen = request.getInputStream().read(buffer, i, contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }
}
